////////////////////////////////////////////////
//we need to declare EVDB.API because it'll be called 
//by the http://api.evdb.com/json response
///////////////////////////////////////////////
if (window.EVDB === undefined) window.EVDB = {};
if (EVDB.API === undefined) EVDB.API = {};
EVDB.API._complete = function(idRequest, oData)
{
  if(window._ev_) window._ev_.complete(idRequest, oData);
}
////////////////////////////////////////////////
Evenful = {};
Eventful = function()
{
  this.idRequest = 1;
  this.requests = [];
  this.events = [];
  this.URL = 'http://api.evdb.com/json';
  this.app_key = 'SfttPGqHWBgfTN6R';
  this.user = null;
  this.user_key = null;
  this.events_per_page = 10;
  this.total_items = null;
  this.page_number = 0;
  this.page_count = null;
  this.search_s = [];
  this.performer_id;
  this.worldwide = false;
  window._ev_ = this;
}

Eventful.inherits(WebService);

Eventful.prototype.displayList = function(events, index){
  var html = ''; 
  for (var e = 0; e < events.length; e++){
    html += '<p><a href="javascript:'+(index >-1?'window._ev_._display()':'Evenful.Desc('+e+')')+'"><b>'+events[e].title+'</b></a><br />';
    
    var str = events[e].start_time;
    var date = str.split(' ');
    var time = date[1].split(':',3);
    date = date[0].split('-',3);


    var when = new Date();
    when.setFullYear(date[0],date[1]-1,date[2]);
    when.setHours(time[0],time[1],time[2]);    
    var address = events[e].venue_address?events[e].venue_address:'';
    var city_name = events[e].city_name?events[e].city_name:'';
    var country_name = events[e].country_name?events[e].country_name:'';
    var postal_code = events[e].postal_code?events[e].postal_code:'';


    html += '<b>When?</b> '+when.toLocaleString()+'<br />'    
    html += '<b>Where?</b> ';
    if (events[e].venue_id)
      html += '<a target="_blank" href="http://eventful.com/venues/'+events[e].venue_id+'">'+events[e].venue_name+'</a>';
    if((address.length+city_name.length+country_name.length+postal_code.length)){
      if(address)html += ', '+address;
      if(city_name.length + postal_code.length + country_name.length)
        html +=' ('+(city_name?city_name+', ':'')+(postal_code?postal_code+', ':'')+(country_name?country_name:'')+')';
    }else html +=' N/A';
  html += '</p>';
 }
 
 if(index >-1){
   html += '<b>Description</b><p>';
   
   try{ if(events[0].image.medium.url) {
          var caption = events[0].image.medium.caption? events[0].image.medium.caption:'Eventful.com image';
          html += '<img style="float:right;" src="'+events[0].image.medium.url+'" title="'+caption+'" alt="'+caption+'" />';
        }
   }catch(e) {}
   var Metallica = this.search_s['artist'];
   html += events[0].description?events[0].description.replace(/Metallica/ig,'<b>'+this.search_s['artist']+'</b>'):'N/A'+'</p>';
 }
 return html;
}
  
Eventful.prototype.search = function(artist, location, pn, worldwide)
{
  if(!this.search_s['artist']){
    this.search_s['artist'] = artist;
    this.search_s['location'] = location;
  }
  this.worldwide = worldwide || !this.search_s['location'].length;
  
  if(!this.performer_id){
    var args = { keywords: this.search_s['artist'], count_only: true, page_size: 5, sort_order: 'member_count',sort_direction: 'ascending', category: 'music' };
    var method = '/performers/search';
  }
  else {
    var loc = this.worldwide?'':this.search_s['location'];
    if(pn !== undefined) this.page_number = pn;
    
    var args = { sort_order: 'date', page_number: this.page_number+1, page_size: this.events_per_page, location: loc, within: 10000000, unit: 'km', category: 'music' };
    var method = '/events/search';
    this.events = [];
  }
  this.jsonCall(method,args);
}

Eventful.prototype.jsonCall = function(sMethod, args)
{
  try {
    if(this.performer_id && (this.events[(args.page_number-1)] != null)) {
        fnCallback(this.events[args.page_number]);
        return;
    }   
    // serialize args if necessary
    if (typeof args == "object")
    {
      // add user-specific details to every call automatically if we have them
      args.app_key = this.app_key;
      if (this.user) args.user = this.user;
      if (this.user_key) args.user_key = this.user_key;

      args = this.serialize(args);
    }
    else
      this.error(null,null,"Eventful.prototype.jsonCall: args must be an object");

    onloading(this.target);
    if(this.performer_id){
      var kw = 'spid:'+this.performer_id.join('+%7C%7C+spid:');
      //for(var i=0; i<this.performer_id.length; i++)
        //kw += 'spid:'+this.performer_id[i]+'+%7C%7C+';
    
      var args2 = '&keywords='+kw+'&json_request_id=';
    }
    else var args2 = '&json_request_id=';
    
    this.JSONcall(this.URL + sMethod +'?'+ args+args2+this.idRequest,'event_json')
  } catch(e) {
      this.error(null,0,e.toString());
  }
}

Eventful.prototype._display = function(ev)
{
  var self = window._ev_;  
  var html = '';
  var events;
  if(!self.performer_id){ // we get the id and make another search to obtain the relevant events
    try {
      self.performer_id = [];
      var total_ev = 0;
      
      for(var i=0; i<parseInt(ev.page_items); i++){
        self.performer_id[i] =  ev.performers.performer[i].id
        total_ev += parseInt(ev.performers.performer[i].event_count);
      }
      //order by number of events
      /*
      for(var i=1; i<ev.page_items; i++){
        for(var j=i; j>0; j--){
          if(ev.performers.performer[j].event_count > ev.performers.performer[j-1].event_count){
            var tmp = ev.performers.performer[j];
            ev.performers.performer[j] = ev.performers.performer[j-1];
            ev.performers.performer[j-1] = tmp;
          }
        }   
      }
      */
      
      if(!total_ev)
        throw "no events found";

      self.search(null,null,null,self.worldwide);
      return;
    }
    catch(e){ }
    
  }
  try
  {
    if(! self.events[self.page_number]) self.events[self.page_number] = ev.events.event;
    events = self.events[self.page_number];
  }
  catch(e) { self.target.innerHTML = '<p>No upcoming events found related with <b>'+self.search_s['artist']+'</b>'+(!self.worldwide?' near '+ self.search_s['location']:'')+'</p>';
             if(self.search_s['location'].length) self.target.innerHTML += '<p>Try to search <a href="javascript: window._ev_.search(\''+self.search_s['artist']+'\',\'\',null,1)">Worldwide</a></p>'; return;}  
  
  html += '<p>We found these events related with <b>'+self.search_s['artist']+'</b>'+
          (!self.worldwide?' near '+ self.search_s['location']+'. Get <a href="javascript: window._ev_.search(\''+self.search_s['artist']+'\',\'\',null,1)">Worldwide</a> events.':' worldwide. '+
          (self.search_s['location'].length?'Get only events near <a href="javascript: window._ev_.search(\''+self.search_s['artist']+'\',\'\')">'+self.search_s['location']+'</a>.':'<a href="http://www.fac​ebook.com/editprofile.php?​contact" target="_blank">Set a city or zip code</a> to get local events.'))+
          '</p>';
  
  // Navigation
  if(self.total_items > self.events_per_page){
    
   html +='<p class="nav">';
    for (var p=0; p<self.page_count; p++){
        if(self.page_number != p)
          html += '<a href="javascript:events.search(\''+encodeURIComponent(self.search_s['artist'])+'\',\''+encodeURIComponent(self.search_s['location'])+'\','+p+','+(self.worldwide?'1':null)+')">'+(p+1)+'</a>';
        else
          html += (p+1);
        if(p != self.page_count -1) html +=' | ';
    }
    html += '</p>';
  }
  
  self.target.innerHTML = html + self.displayList(events);
  
  self.idRequest++;
}

Eventful.prototype.complete = function(idRequest, oData)
{
      this.total_items = oData.total_items;
      this.page_number = --oData.page_number;
      this.page_count = oData.page_count;

      // fire the callback with the data
      this._display(oData);
}

Eventful.prototype.login = function(nonce, password)
{
  if(typeof window.binl2b64 != 'function'){
    if(this.loadedJSON) return;
    this.JSONcall('http://pickstation.com/giacomo/js/md5.js');
    var timeID = setInterval(window._ev_.login,400,nonce,password);
    this.loadedJSON = timeID;
    return;
  }
  
  if(_ev_) clearInterval(_ev_.loadedJSON);
  _ev_.loadedJSON = null;
  var args = {user:window._ev_.user,nonce:nonce,response:''};
  
}

Evenful.Desc = function(ev_index)
{
  if(ev_index === undefined) return;
  var self = window._ev_;
  var ev = self.events[self.page_number][ev_index];
  
  self.target.innerHTML = '<p><a href="javascript:window._ev_._display()">Back to event list</a> | <a target="_blank" href="http://eventful.com/events/'+ev.id+'">Eventful.com direct link</a></p>'+
  self.displayList(new Array(ev), ev_index);
}
